package cn.easyplatform.studio.web.controller.admin;


import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.admin.LoginlogAddCmd;
import cn.easyplatform.studio.context.Contexts;
import cn.easyplatform.studio.vos.LoginUserVo;
import cn.easyplatform.studio.vos.LoginlogVo;
import org.zkoss.zk.ui.Executions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author Zeta
 * @Version 1.0
 */


public class LoginLogListener {

    private static String type;//1 登录  2正常退出  3超时退出  4管理员移除
    private static List<LoginlogVo> list = new ArrayList<LoginlogVo>();
    private static Map<String, Object> userMap = new ConcurrentHashMap<String, Object>();

    public static synchronized void loginLog() {

        String userId = Contexts.getUser().getUserId();
        String roleId = Contexts.getUser().getRoleId();
        //LoginlogVo loginlog = StudioApp.execute(new GetOnlineUserCmd(userId, roleId));
        LoginlogVo loginlog = new LoginlogVo();
        loginlog.setUserId(Contexts.getUser().getUserId());
        loginlog.setUserName(Contexts.getUser().getName());
        if (LoginUserVo.UserType.ADMIN.getName().equals(roleId)) {
            loginlog.setUserType("1");//0,1
            loginlog.setRoleName("超级管理员");//超级管理员
        } else {
            loginlog.setUserType("0");
            loginlog.setRoleName(roleId);
        }

        HttpServletRequest request = (HttpServletRequest) Executions.getCurrent().getNativeRequest();
        String ipAddress = getIPAddress(request);

        String userAgent = Executions.getCurrent().getUserAgent();
        String[] userAgents = userAgent.split(" ");
        String loginOS = userAgents[1].substring(1);
        String loginTN = userAgents[userAgents.length - 2] + " " + userAgents[userAgents.length - 1];

        HttpSession session = request.getSession();

        Date date = new Date();
        type = "1";
        loginlog.setIpAddress(ipAddress);
        loginlog.setLoginOS(loginOS);
        loginlog.setLoginTN(loginTN);
        loginlog.setSession(session);
        loginlog.setLoginTime(date);
        loginlog.setType(type);

        StudioApp.execute(new LoginlogAddCmd(loginlog));
        userMap.put(userId, loginlog);
    }

    public static synchronized void timeOutLog(LoginUserVo userVo) {

        LoginlogVo loginlog = (LoginlogVo)userMap.get(userVo.getUserId());

        Date date = new Date();
        type = "3";
        loginlog.setLoginTime(date);
        loginlog.setType(type);

        list.add(loginlog);
        userMap.remove(userVo.getUserId());
    }

    public static synchronized void loginOutLog() {

        String userId = Contexts.getUser().getUserId();
        LoginlogVo loginlog = (LoginlogVo)userMap.get(userId);

        Date date = new Date();
        type = "2";

        loginlog.setLoginTime(date);
        loginlog.setType(type);
        list.add(loginlog);
        for(int i=0;i<list.size();i++){
            StudioApp.execute(new LoginlogAddCmd(list.get(i)));
        }
        list.clear();
        userMap.remove(userId);
    }

    public static synchronized void RemoveLog(LoginlogVo log) {

        Date date = new Date();
        type = "4";

        log.setLoginTime(date);
        log.setType(type);

        StudioApp.execute(new LoginlogAddCmd(log));
        userMap.remove(log.getUserId());
    }


    public static String getIPAddress(HttpServletRequest request) {
        String IPAddress = request.getHeader("X-Forwarded-For");
        if (IPAddress == null || IPAddress.length() == 0 || "unknown".equalsIgnoreCase(IPAddress)) {
            IPAddress = request.getHeader("Proxy-Client-IP");
        }
        if (IPAddress == null || IPAddress.length() == 0 || "unknown".equalsIgnoreCase(IPAddress)) {
            IPAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (IPAddress == null || IPAddress.length() == 0 || "unknown".equalsIgnoreCase(IPAddress)) {
            IPAddress = request.getHeader("HTTP_CLIENT_IP");
        }
        if (IPAddress == null || IPAddress.length() == 0 || "unknown".equalsIgnoreCase(IPAddress)) {
            IPAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (IPAddress == null || IPAddress.length() == 0 || "unknown".equalsIgnoreCase(IPAddress)) {
            IPAddress = request.getRemoteAddr();
        }
        if (IPAddress.equals("127.0.0.1") || IPAddress.equals("0:0:0:0:0:0:0:1")) {
            InetAddress inet = null;
            try {
                inet = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            IPAddress = inet.getHostAddress();
        } else if (IPAddress.length() > 15) {
            String[] ips = IPAddress.split(",");
            IPAddress = ips[0];
        }
        return IPAddress;
    }

    public static synchronized List<LoginlogVo> getAllOnlineUser() {
        List<LoginlogVo> onlineUserList = new ArrayList<>();
        for (Map.Entry<String, Object> entry : userMap.entrySet()) {
            onlineUserList.add((LoginlogVo) entry.getValue());
        }
        return onlineUserList;
    }

    public static synchronized List<LoginlogVo> getOnlineUserByUserId(String userId) {
        List<LoginlogVo> onlineUser = new ArrayList<>();
        if(null==userMap.get(userId) || ("").equals(userMap.get(userId))){
            return onlineUser;
        }else {
            onlineUser.add((LoginlogVo) userMap.get(userId));
        }
        return onlineUser;
    }

}


